package com.csc531.lists;

import java.util.ArrayList;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.csc531.Manager;
import com.csc531.R;
import com.csc531.DataTypes.Task;
import com.csc531.adapters.ClassesDbAdapter;
import com.csc531.adapters.ClassesListAdapter;
import com.csc531.edit.ClassesEdit;


/**
 * @author Javier Figueroa
 *
 */


public class ClassesThinList extends ThinList 
{
	//logging
	private static final String TAG = "CLASSES TAB";
	
	//activity results
	public static final int ACTIVITY_CREATE=0;
	public static final int ACTIVITY_EDIT=1;

	//menu
	private static final int INSERT_ID = Menu.FIRST;
	private static final int EDIT_ID = Menu.FIRST + 1;
	private static final int DELETE_ID = Menu.FIRST + 2;
	private static final int SWITCH_TO_FATLIST = Menu.FIRST + 3;

	//globals
	private ArrayList<Integer> _tasksDatabaseRowIds;
	private ClassesDbAdapter _mDbHelper;
	

	//---------------------------------------------------------------------------------
	

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{
        super.onActivityResult(requestCode, resultCode, intent);
        fillTaskListData();
        
    }
	
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		((ClassesListAdapter)getListAdapter()).toggle(position);
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, SWITCH_TO_FATLIST, 0, R.string.menu_switch_to_fatlist);
		menu.add(0, INSERT_ID, 0, R.string.menu_insert);
		menu.add(0, EDIT_ID, 0, R.string.menu_edit);
		menu.add(0, DELETE_ID, 0,  R.string.menu_delete);
		
		return true;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		switch(item.getItemId()) 
		{
		case INSERT_ID:
			createTask();
			return true;
		case EDIT_ID:
			editTask();
			return true;
		case DELETE_ID:
			deleteTask();
			fillTaskListData();
			return true;
		case SWITCH_TO_FATLIST:
			switchToViewByClass();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}
	


	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		_mDbHelper = new ClassesDbAdapter(this);
		_mDbHelper.open();
		fillTaskListData();
	}

	/**
	 * Fill the tab with a list object containing the tasks
	 */
	private void fillTaskListData() 
	{

		ClassesListAdapter classesTabAdapter = new ClassesListAdapter(this);
		_tasksDatabaseRowIds = new ArrayList<Integer>();
		
		Cursor taskCursor = _mDbHelper.fetchAllTasks();
		startManagingCursor(taskCursor);
		
        String[] from = new String[]{ClassesDbAdapter.KEY_TITLE};
        int[] to = new int[]{R.id.text1};
        
        SimpleCursorAdapter simpleTaskCursor = 
        	    new SimpleCursorAdapter(this, R.layout.notes_row, taskCursor, from, to);
       
        printTasksToClassesTab(simpleTaskCursor,classesTabAdapter);

		classesTabAdapter.setExpandedPropertyOnList();
		setListAdapter(classesTabAdapter);
	}
	
	/**
	 * Queries the SQLlite to populate the contents of the tab
	 * @param simpleNoteCursor
	 * @param notesTabAdapter
	 */
	private void printTasksToClassesTab(SimpleCursorAdapter simpleTaskCursor, ClassesListAdapter classesTabAdapter)
	{
		 try 
		 {
	        	simpleTaskCursor.getCursor().moveToFirst();
	            
	    		int numberOfRows = simpleTaskCursor.getCursor().getCount();
	    		int numberOfColumns = simpleTaskCursor.getCursor().getColumnCount();

	    		Log.v(TAG, "num of rows: "+numberOfRows);
	    		Log.v(TAG, "num of cols: "+numberOfColumns);
	    		
	    		for( int i = 0; i < numberOfRows ; i++ )
	    		{
	    			addTasksToCourse(simpleTaskCursor,classesTabAdapter);
	    			
	    			simpleTaskCursor.getCursor().moveToNext();
	    		}
	    		
	     } 
		 catch(RuntimeException ex)
		 {
	        	Log.v(TAG,"The List is Empty!!");
	     }
	}
	
	/**
	 * Traverses the database table and creates Course objects and appends Tasks objects to them
	 * @param simpleNoteCursor
	 * @param notesTabAdapter
	 */
	private void addTasksToCourse(SimpleCursorAdapter simpleTaskCursor, ClassesListAdapter classesTabAdapter) 
	{
		int k = 0;
		
		String rowId = simpleTaskCursor.getCursor().getString(k++);
		_tasksDatabaseRowIds.add(Integer.parseInt(rowId));
		
		String courseName = simpleTaskCursor.getCursor().getString(k++);
		Task task = new Task();
		task.setCourseName(courseName);

		String dueDate = simpleTaskCursor.getCursor().getString(k++);
		task.setDate(dueDate);
		
		String title = simpleTaskCursor.getCursor().getString(k++);
		task.setTitle(
				title +
				" - (" + task.getCourseName() + ")" +
				" - " + task.getDate()
				);

		String description = simpleTaskCursor.getCursor().getString(k++);
		task.setDescription(description);
		
		classesTabAdapter.addCourse(task);
	}

	/**
	 * Action method to switch to the "View By Class" list type. 
	 */
	private void switchToViewByClass()
	{
		Intent i = new Intent(this, Manager.class);
		i.putExtra("TAB", Manager.CLASSES_TAB);
		i.putExtra("CLASSESVIEWTYPE", Manager.CLASSES_FATLIST);
		startActivity(i);
		
	}
	
	/**
	 * Action method that creates a new Task
	 */
	private void createTask() 
	{
		Intent i = new Intent(this, ClassesEdit.class);
		startActivityForResult(i, ACTIVITY_CREATE);
	}
	
	/**
	 * Action method to edit a selected task
	 */
	private void editTask() 
	{
		Intent i = new Intent(this, ClassesEdit.class);
		
		if(checkTasksExist() == false) 
		{
			return;
		}
		
		long id = _tasksDatabaseRowIds.get((int) getSelectedItemId());
		
		Log.v(TAG, "The id from onlistitemclick is: "+id);

		i.putExtra(ClassesDbAdapter.KEY_ROWID,id);
		startActivityForResult(i, ACTIVITY_EDIT);
	}
	
	/**
	 * Action method to delete a selected task
	 */
	private void deleteTask() 
	{
		if(checkTasksExist() == false) 
		{
			return;
		}
		
		_mDbHelper.deleteTask(_tasksDatabaseRowIds.get((int) getListView().getSelectedItemId()));
	}
	
	/**
	 * Helper method to prevent OutOfBoundsException in the
	 * _tasksDatabaseRowIds ArrayList
	 * 
	 * @return false if the ArrayList is empty
	 */
	private boolean checkTasksExist() 
	{
		if(_tasksDatabaseRowIds.size() <= 0) 
		{
			return false;
		}
		else 
		{
			return true;
		}
	}



}
